package com.example.its2021606134chh.LoginModule;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.its2021606134chh.MainActivity;
import com.example.its2021606134chh.R;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.jetbrains.annotations.NotNull;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/*
 *1、用户名和密码输入只能是一行输入，并且在用户名输入完成后，点击软键盘的“下一项”键，键盘焦点自动切换到密码输入框；
 * 密码输入完成后，点击软键盘的“完成”键，软键盘隐藏。
 * 2、实现记住密码功能和自动登录功能
 * 3、点击注册或网络设置跳转或弹出对应功能界面。
 * 注：登录默认账户的用户名是admin，密码是admin。
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    private TextView tvNetWork;
    private EditText edtUserName;
    private EditText edtPwd;
    private CheckBox Remember;
    private Boolean RememberFlag = false;
    private CheckBox AutoLogin;
    private Boolean AutoLoginFlag = false;
    private Button btnLogin;
    private Button btnRegist;
    private String username;
    private String password;
    private ProgressDialog progressDialog;
    private String url = "http://121.9.253.237:8888/traffic/api/v2/user_login";
    OkHttpClient okHttpClient = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();

//        使用SharedPreferences记录登录数据
        SharedPreferences sp = getSharedPreferences("login_test01", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (sp != null) {    //有记录
            username = sp.getString("username", "");
            password = sp.getString("password", "");
            RememberFlag = sp.getBoolean("remember", false);
            AutoLoginFlag = sp.getBoolean("auto", false);
            edtUserName.setText(username);
        }

        if (RememberFlag) { //记住密码
            Remember.setChecked(true);
            edtPwd.setText(password);
        }
        if (AutoLoginFlag){ //自动登录
            AutoLogin.setChecked(true);
//            一次自动登录
            AutoLoginFlag = false;
            editor.putBoolean("auto", false);
            editor.commit();

            login(username, password);
        }

//                记住密码
        Remember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                如果选中的是记住密码，则取消记住密码、自动登录
                if (!isChecked) {
                    AutoLogin.setChecked(false);
                    edtPwd.setText("");
                }
            }
        });

        btnLogin.setOnClickListener(this);
        btnRegist.setOnClickListener(this);
        tvNetWork.setOnClickListener(this);
    }

    private void initView() {
        tvNetWork = (TextView) findViewById(R.id.tvNetWork);
        edtUserName = (EditText) findViewById(R.id.edtUserName);
        edtPwd = (EditText) findViewById(R.id.edtPwd);
        Remember = (CheckBox) findViewById(R.id.Remember);
        AutoLogin = (CheckBox) findViewById(R.id.AutoLogin);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnRegist = (Button) findViewById(R.id.btnRegist);
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogin:

//              取得用户名密码
                String username = edtUserName.getText().toString().trim();
                String password = edtPwd.getText().toString().trim();

//                使用SharedPreferences缓存数据
                SharedPreferences sharedPreferences = getSharedPreferences("login_test01", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("username", username); //写入值

//                选中记住密码
                if (Remember.isChecked()) {
                    editor.putBoolean("remember", true);
                    editor.putString("password", password);

//                    选中自动登录
                    if (AutoLogin.isChecked()){
                        AutoLoginFlag = true;
                    } else {
                        AutoLoginFlag = false;
                    }
                    editor.putBoolean("auto", AutoLoginFlag);

                } else {
//                    取消自动登录和记住密码,清空密码
                    RememberFlag = false;
                    AutoLoginFlag = false;
                    editor.putString("password", "");
                    editor.putBoolean("remember", RememberFlag);
                    editor.putBoolean("auto", AutoLoginFlag);
                }
//                提交
                editor.commit();

                login(username, password);
                break;
            case R.id.btnRegist:
                register();
                break;
            case R.id.tvNetWork:
                dialogueBox();
                break;
            default:
                break;
        }
    }

//    网络设置
    public void dialogueBox(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);
        View view = LayoutInflater.from(this.getBaseContext()).inflate(R.layout.activity_network_dialog,null,false);
        dialog.setView(view);

        Button btnNetworkSave = (Button)view.findViewById(R.id.btnNetworkSave);
        EditText edtNetworkIP = (EditText)view.findViewById(R.id.edtNetworkIP);
        Button btnNetworkCancel = (Button)view.findViewById(R.id.btnNetworkCancel);

        AlertDialog mdialog = dialog.show();

        btnNetworkSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String IP = edtNetworkIP.getText().toString();
                Boolean isIP = isIP(IP);
                if (isIP) {
                    Toast.makeText(LoginActivity.this,IP,Toast.LENGTH_SHORT).show();
                    mdialog.dismiss();
                } else {
                    Toast.makeText(LoginActivity.this,"IP地址格式出错",Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnNetworkCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mdialog.dismiss();
            }
        });
    }

//    IP格式判断方法
    public boolean isIP(String addr)
    {
        if(addr.length() < 7 || addr.length() > 15 || "".equals(addr))
        {
            return false;
        }
        /**
         * 判断IP格式和范围
         */
        String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pat = Pattern.compile(rexp);
        Matcher mat = pat.matcher(addr);
        boolean ipAddress = mat.find();
        //============对之前的ip判断的bug在进行判断
        if (ipAddress==true){
            String ips[] = addr.split("\\.");
            if(ips.length==4){
                try{
                    for(String ip : ips){
                        if(Integer.parseInt(ip)<0||Integer.parseInt(ip)>255){
                            return false;
                        }
                    }
                }catch (Exception e){ return false; }
                return true;
            } else { return false; }
        }
        return ipAddress;
    }

//    登录验证
    private void login(String logusername, String logpassword) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("UserName", logusername);
                jsonObject.addProperty("UserPwd", logpassword);
                String json = jsonObject.toString();
                MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                RequestBody requestBody = RequestBody.create(json, mediaType);
                Request request = new Request.Builder().url(url).post(requestBody).build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String result = response.body().string();
                        Log.i("TAG", "onResponse: "+result);
                        Gson gson = new Gson();
                        params params = gson.fromJson(result, params.class);
                        Log.i("TAG", "onResponse: "+params.getRESULT());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (params.getRESULT().equals("S")) {
                                    progressDialog = new ProgressDialog(LoginActivity.this);
                                    progressDialog.setTitle("正在登陆...");
                                    progressDialog.setMessage("请稍后...");
                                    progressDialog.show();
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else if (params.getRESULT().equals("F")) {
                                    progressDialog = new ProgressDialog(LoginActivity.this);
                                    progressDialog.setTitle("登陆失败");
                                    progressDialog.setMessage("账号或密码错误");
                                    progressDialog.show();
                                }

                            }
                        });
                    }
                });
            }
        }).start();

    }

    private void register() {
        Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
        startActivity(intent);
        this.finish();
    }

}